<?php

namespace App\Common\Traits;

use Illuminate\Support\Str;

trait CaptchaTrait
{

    //生成验证码
    public function generateCaptcha(){
        /*定义头文件为图片,直接输出图片流*/
        //header("Content-type: image/png");

        /*生成验证码*/
        /*创建图片设置字体颜色*/
        $w=100;
        $h=24;
        $im = imagecreate($w, $h);

        /*随机生成两个数字*/
        $num1 = mt_rand(1, 30);
        $num2 = mt_rand(1, 30);

        /*结果存入session或者缓存*/
        $res=$num1+$num2;
//        $_SESSION ["captcha_plus_result"] = $res;
        $cacheKey="ck_".Str::random(16);
        cache([$cacheKey=>$res],600);

        /*设置图片背景颜色*/
        $imgBackColor = imagecolorallocate($im, mt_rand(10, 150), mt_rand(10, 150), mt_rand(10, 150));
        /*创建图片背景*/
        imagefilledrectangle($im, 0, 0, $w, $h, $imgBackColor);

        /*在画布上随机生成大量点*/
        for ($i = 0; $i < 150; $i++) {
            $pixelColor = imagecolorallocate($im, mt_rand(10, 150), mt_rand(10, 155), mt_rand(10, 155));
            imagesetpixel($im, mt_rand(0, $w), mt_rand(0, $h), $pixelColor);
        }

        //浅色颜色
        $color1 = imagecolorallocate($im, mt_rand(90, 255), mt_rand(90, 255), mt_rand(90, 255));
        $color2 = imagecolorallocate($im, mt_rand(90, 255), mt_rand(90, 255), mt_rand(90, 255));
        $color3 = imagecolorallocate($im, mt_rand(90, 255), mt_rand(90, 255), mt_rand(90, 255));
        $color4 = imagecolorallocate($im, mt_rand(90, 255), mt_rand(90, 255), mt_rand(90, 255));
        $color5 = imagecolorallocate($im, mt_rand(90, 255), mt_rand(90, 255), mt_rand(90, 255));

        /*将计算验证码写入到图片中*/
        imagestring($im, mt_rand(4, 6), mt_rand(1, 7), mt_rand(1, 9), $num1, $color1);
        imagestring($im, mt_rand(4, 6), mt_rand(20, 35), mt_rand(1, 9), "+", $color2);
        imagestring($im, mt_rand(4, 6), mt_rand(47, 55), mt_rand(1, 9), $num2, $color3);
        imagestring($im, mt_rand(4, 6), mt_rand(67, 75), mt_rand(1, 9), "=", $color4);
        imagestring($im, mt_rand(4, 6), mt_rand(86, 90), mt_rand(1, 9), "?", $color5);

        /*输出图片*/
        imagepng($im);

        //获取图片数据
        $content = ob_get_clean();

        /*销毁图片*/
        imagedestroy($im);

        return [
            'captcha_key'=>$cacheKey,
            'captcha_img'=>'data:image/png;base64,' . base64_encode($content),
        ];
    }

}
